﻿using BooksLib.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BooksLib.Repositories
{
    public class StudentSampleRepository : IStudent
    {
        private List<Student> _Students;
        public StudentSampleRepository()
        {
            //初始化仓储（当前数据源来自列表）
            InitSampleBooks();
        }

        /// <summary>
        /// 初始化数据仓库，当前数据源来自列表
        /// </summary>
        private void InitSampleBooks()
        {
            _Students = new List<Student>()
            {
                new Student { StudentId = 1, StudentName = "aa", Gender = "男" },
                new Student { StudentId = 2, StudentName = "bb", Gender = "女" },
                new Student { StudentId = 3, StudentName = "cc", Gender = "女" }
            };
        }
        /// <summary>
        /// 异步删除指定id的学生信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns>返回bool值</returns>
        public Task<bool> DeleteAsync(int id)
        {

            Student bookToDelete = _Students.Find(b => b.StudentId == id);
            if (bookToDelete != null)
            {
                //_books.Remove(bookToDelete)，其中_books是List集合，其中Remove方法是同步方法
                //当前方法要求返回值是在异步任务下返回bool
                //因此，使用Task.FromResult将同步方法调用结果，以成功的异步任务形式返回
                return Task.FromResult<bool>(_Students.Remove(bookToDelete));
            }

            return Task.FromResult<bool>(false);
        }

        /// <summary>
        /// 异步获取指定id的学生信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns>返回书</returns>
        public Task<Student> GetItemAsync(int id)
        {
            //使用Task.FromResult将同步方法调用结果，以成功的异步任务形式返回
            return Task.FromResult(_Students.Find(b => b.StudentId == id));
        }

        /// <summary>
        /// 异步获取所有学生的信息
        /// </summary>
        /// <returns></returns>
        public Task<IEnumerable<Student>> GetItemsAsync()
        {
            return Task.FromResult<IEnumerable<Student>>(_Students);
        }

        /// <summary>
        /// 异步更新某个学生的信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns>返回更新后的书</returns>
        public Task<Student> UpdateAsync(Student item)
        {
            Student StudentUpdate = _Students.Find(b => b.StudentId == item.StudentId);
            if (StudentUpdate == null) return null;
            int ix = _Students.IndexOf(StudentUpdate);
            _Students[ix] = item;
            return Task.FromResult(_Students[ix]);
        }
        /// <summary>
        /// 异步添加学生信息到存储库
        /// </summary>
        /// <param name="item"></param>
        /// <returns>返回添加后的学生信息</returns>

        public Task<Student> AddAsync(Student item)
        {

            item.StudentId = _Students.Select(b => b.StudentId).Max() + 1;
            _Students.Add(item);
            return Task.FromResult(item);
        }
    }
}
